package com.tanhua.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.dubbo.api.SoulTestApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.enums.Nature;
import com.tanhua.dubbo.enums.ScoreType;
import com.tanhua.dubbo.enums.SideType;
import com.tanhua.dubbo.pojo.*;
import com.tanhua.server.vo.QuestionsVo;
import com.tanhua.server.vo.SimilarYou;
import com.tanhua.server.vo.TestReportVo;
import com.tanhua.server.vo.TestSoulVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class SoulService {

    @DubboReference(version = "1.0.0")
    private SoulTestApi soulTestApi;

    @DubboReference(version = "1.0.0")
    private UserInfoApi userInfoApi;

    /**
     * 查询所需要的问卷列表
     * @return
     */
    public Object findQuestionQueue() {
        Long userId = UserThreadLocal.get();
        List<TestSoul> soulQueue = this.soulTestApi.findSoulQueue(userId);
        if (CollUtil.isEmpty(soulQueue)){
            return Collections.emptyList();
        }
        //查询最新一次报告,
        TestReport report = this.soulTestApi.findReport(null, userId);
        return soulQueue.stream().map(soulTest -> {
            TestSoulVo testSoulVo = BeanUtil.toBeanIgnoreError(soulTest, TestSoulVo.class);
            testSoulVo.setLevel(soulTest.getLevel().toString());
            testSoulVo.setName(soulTest.getNameType().toString());
            testSoulVo.setQuestions(soulTest.getQuestions().stream().map(questions ->
                    BeanUtil.toBeanIgnoreError(questions, QuestionsVo.class))
                    .collect(Collectors.toList()));
            if (report != null){
                testSoulVo.setReportId(report.getId().toHexString());
            }
            return testSoulVo;
        }).collect(Collectors.toList());
    }
    /**
     * 提交问卷
     * @param object
     * @return
     */
    public Object questionPost(Object object) {
        List<Map<String, Object>> list=(List<Map<String, Object>> )object;
        Long userId = UserThreadLocal.get();
        //设定一个得分
        int sum=0;
        for (Map<String, Object> map : list) {
            String questionId = (String) map.get("questionId");
            Questions questions = this.soulTestApi.findById(questionId);
            String optionId = (String) map.get("optionId");
            List<Map<String, Integer>> list1 = questions.getSideScores();

            for (Map<String, Integer> map1 : list1) {
                Integer score = map1.get(optionId);
                if (score != null){
                    sum+=score;
                    break;
                }
            }
        }
        TestReport testReport = new TestReport();
        testReport.setId(ObjectId.get());
        testReport.setUserId(userId);
        //根据得分生成一个report
        //图片,默认
        String [] arr={"https://tanhua-dev.oss-cn-zhangjiakou.aliyuncs.com/images/test_soul/owl.png",
        "https://tanhua-dev.oss-cn-zhangjiakou.aliyuncs.com/images/test_soul/rabbit.png",
        "https://tanhua-dev.oss-cn-zhangjiakou.aliyuncs.com/images/test_soul/fox.png",
        "https://tanhua-dev.oss-cn-zhangjiakou.aliyuncs.com/images/test_soul/lion.png"};
        if (sum<21){
            testReport.setNature(Nature.OWL);
            Dimension dimension= new Dimension();
            dimension.setScoreType("70%");
            dimension.setSideType("内向");
            Dimension dimension1= new Dimension();
            dimension1.setScoreType("75%");
            dimension1.setSideType("理性");
            Dimension dimension2= new Dimension();
            dimension2.setScoreType("80%");
            dimension2.setSideType("判断");
            Dimension dimension3= new Dimension();
            dimension3.setScoreType("60%");
            dimension3.setSideType("可靠");

            testReport.setDimensions(Arrays.asList(dimension,dimension1,dimension2,dimension3));
            testReport.setCover(arr[0]);
        }else if(sum >21 && sum<40){
            testReport.setNature(Nature.WR);
            Dimension dimension= new Dimension();
            dimension.setScoreType("70%");
            dimension.setSideType("稳定");
            Dimension dimension1= new Dimension();
            dimension1.setScoreType("75%");
            dimension1.setSideType("友善");
            Dimension dimension2= new Dimension();
            dimension2.setScoreType("80%");
            dimension2.setSideType("耐心");
            Dimension dimension3= new Dimension();
            dimension3.setScoreType("80%");
            dimension3.setSideType("可靠");
            testReport.setDimensions(Arrays.asList(dimension,dimension1,dimension2,dimension3));
            testReport.setCover(arr[1]);
        }else if (sum >41 && sum<55){
            testReport.setNature(Nature.FOX);
            Dimension dimension= new Dimension();
            dimension.setScoreType("70%");
            dimension.setSideType("外向");
            Dimension dimension1= new Dimension();
            dimension1.setScoreType("75%");
            dimension1.setSideType("自信");
            Dimension dimension2= new Dimension();
            dimension2.setScoreType("80%");
            dimension2.setSideType("乐观");
            Dimension dimension3= new Dimension();
            dimension3.setScoreType("60%");
            dimension3.setSideType("热情");
            testReport.setDimensions(Arrays.asList(dimension,dimension1,dimension2,dimension3));
            testReport.setCover(arr[2]);
        }else if (sum>56){
            Dimension dimension= new Dimension();
            dimension.setScoreType("70%");
            dimension.setSideType("外向");
            Dimension dimension1= new Dimension();
            dimension1.setScoreType("75%");
            dimension1.setSideType("自信");
            Dimension dimension2= new Dimension();
            dimension2.setScoreType("80%");
            dimension2.setSideType("果断");
            Dimension dimension3= new Dimension();
            dimension3.setScoreType("90%");
            dimension3.setSideType("强势");
            testReport.setNature(Nature.LION);
            testReport.setDimensions(Arrays.asList(dimension,dimension1,dimension2,dimension3));
            testReport.setCover(arr[3]);
        }
        //插入生成报告
        testReport.setCreated(System.currentTimeMillis());
        this.soulTestApi.questionGet(testReport);

       return testReport.getId().toHexString();
    }

    /**
     * 查看结果
     * @param soulId
     * @return
     */
    public Object findReport(String soulId) {
        Long userId = UserThreadLocal.get();
        TestReport report = this.soulTestApi.findReport(soulId, userId);
        if (null ==report){
            //第一次点击查看测试报告不给回应
            return null;
        }
        String [] arrStr={"猫头鹰：他们的共同特质为重计划、条理、细节精准。在行为上，表现出喜欢理性思考与分析、较重视制度、" +
                " 结构、规范。他们注重执行游戏规则、循规蹈矩、巨细靡遗、重视品质、敬业负责。,白兔型：平易近人、" +
                "  敦厚可靠、避免冲突与不具批判性。在行为上，表现出不慌不忙、冷静自持的态度。他们注重稳定与中长程规划，" +
                " 现实生活中，常会反思自省并以和谐为中心，即使面对困境，亦能泰然自若，从容应付。",
                "白兔型：平易近人、敦厚可靠、避免冲突与不具批判性。在行为上，表现出不慌不忙、冷静自持的态度。" +
                        "他们注重稳定与中长程规划，现实生活中，常会反思自省并以和谐为中心，" +
                        "即使面对困境，亦能泰然自若，从容应付。",
                "狐狸型：人际关系能力极强，擅长以口语表达感受而引起共鸣，很会激励并带动气氛。" +
                   " 他们喜欢跟别人互动，重视群体的归属感，基本上是比较「人际导向」。由于他们富同理心并乐于分享，" +
                   " 具有很好的亲和力，在服务业、销售业、传播业及公共关系等领域中，狐狸型的领导者都有很杰出的表现。,"
                        ,
                " 狮子型：性格为充满自信、竞争心强、主动且企图心强烈，是个有决断力的领导者。一般而言，" +
                        " 狮子型的人胸怀大志，勇于冒险，看问题能够直指核心，并对目标全力以赴。" +
                        " 他们在领导风格及决策上，强调权威与果断，擅长危机处理，此种性格最适合开创性与改革性的工作。"};
        TestReportVo testReportVo = new TestReportVo();
        testReportVo.setConclusion(arrStr[report.getNature().getValue()]);
        testReportVo.setCover(report.getCover());
        testReportVo.setDimensions(report.getDimensions().stream().map(dimension -> {
            Map<String, String> map = new HashMap<>();
            map.put("key", dimension.getSideType());
            map.put("value",dimension.getScoreType());
            return map;
        }).collect(Collectors.toList()));
        //查询相似性格的人
        List<Object> userIdList=this.soulTestApi.findAsReport(report.getNature().toString(),userId);
        if (CollUtil.isEmpty(userIdList)){
            //没有数据的情况下直接返回
            userIdList=Arrays.asList(5,6,7,8,9,10);
        }
        List<UserInfo> infoList = this.userInfoApi.queryByUserIdList(userIdList);

        testReportVo.setSimilarYou(infoList.stream()
                .map(userInfo -> BeanUtil.toBeanIgnoreError(userInfo, SimilarYou.class))
                .collect(Collectors.toList()));
        return testReportVo;
    }
}
